<?php
require_once( '../system/smarty.inc' );
require_once( '../system/mdao/Class_M_MATRIX.php' );
require_once( '../system/mdao/Class_M_MATRIX_VER.php' );
require_once( '../system/mdao/Class_M_OTHER.php' );
require_once( '../system/Class_ERROR.php' );
require_once( '../system/Class_PWD.php' );
require_once( '../system/login.inc.php' );
require_once( '../system/aoki_m_plus.php' );

Class_PWD::valid_auth(AOKI_AUTH_MATRIX,$login['staff_auth']);

$dao  = new Class_M_MATRIX_VER ;
$dao1 = new Class_M_MATRIX  ;
$ispost = false;

$isG7  = FALSE;
if   ($login['staff_auth'] == 'G-7') {
	$isG7 = TRUE;
}

$arrmst   = Class_M_OTHER::get_matrix_mst_array("ALL");
$patterns = Class_M_OTHER::get_pattern_array( NULL, '23');

if( $_SERVER['REQUEST_METHOD'] == 'GET' ){
	$phase = 'input';
	if( isset($_GET['id']) && $_GET['id'] != '' ){
		$matrix_cd   = $_GET['id'];
	}else{
		//$forms['auth'] = 0;
		echo "パラメタエラー";
		exit;
	}
	
}else{
	$forms = $_POST;
	$matrix_cd   = $forms["matrix_cd"];
	if( $forms['mode'] == 'input' ){
		//フォームデータ整形
		$values  = array();
		$vidarr  = array();
		$ispost = true;
		foreach ($forms["size"] as $k => $v ) {
			
			$values[$k]["matrix_cd"]       = $forms["matrix_cd"];
			$values[$k]["groupid"]         = $forms["groupid"];
			
			$values[$k]["title"]           = $forms["title"];
			
			$values[$k]["color"]           = $forms["color"];
			$values[$k]["sale_name"]       = $forms["sale_name"];
			$values[$k]["oper"]            = $forms["oper"];
			
			$vidarr[$k]                    = $forms["id"][$k] ;
			
			$values[$k]["verno"]           = $forms["verno"][$k];
			$values[$k]["size"]            = $forms["size"][$k] ;
			$values[$k]["contractor"]      = $forms["contractor"][$k] ;
			$values[$k]["print"]           = $forms["print"][$k] ;
			//$values[$k]["area_id"]       = $forms["area_id"][$k] ;
			$values[$k]["area"]            = $forms["area"][$k] ;
			$values[$k]["area_id"]         = empty($forms["area"][$k]) ? 0 : current(array_keys($arrmst[3],$forms["area"][$k] ));
			
			$values[$k]["pattern_cd"]      = empty($forms["pattern_name"][$k])  ?  0 :    current(array_keys($patterns,$forms["pattern_name"][$k] )) ;
			//[]
			
			$values[$k]["mano_out"]        = $forms["mano_out"][$k] ;
			$values[$k]["mano_in"]         = $forms["mano_in"][$k] ;
			
			$values[$k]["perweekver"]      = $forms["perweekver"][$k] ;
			$values[$k]["map"]             = $forms["map"][$k] ;
			$values[$k]["saletickt"]         = $forms["saletickt"][$k] ;
			
			$values[$k]["exp_ins_flg"]     = $forms["exp_ins_flg"][$k] ;
			
	
			if (strlen($forms["exp_ins_week"][$k]) >= 10) {
				$values[$k]["exp_ins_week"]    = Class_PWD::date_to_int8(substr($forms["exp_ins_week"][$k],0, 10)) ;
			} else {
				$values[$k]["exp_ins_week"] = 0;
			}
			
			$values[$k]["memo"]            = $forms["memo"][$k] ;
			$values[$k]["memoprinter"]     = $forms["memoprinter"][$k] ;
			$values[$k]["user_flag"]       = $forms["user_flag"][$k] ;
			$values[$k]["memoprinter"]     = $forms["memoprinter"][$k] ;
			
			$values[$k]["titlecell"]       = $forms["title"]."(".$values[$k]["area"].")".$values[$k]["size"] ;
			
		}
		
		$err     = new Class_ERROR("","");
		$chk     = $dao->get_checks();
		$err_flg = false;
		$maxlens = $dao->get_maxlens();
		
		foreach ($values as $k => $v ) {
			//if ($v["user_flag"] == '9') {
			//	continue;
			//}
			foreach ($chk as $kcol => $chkval) {
				$err_mes[$kcol]  = $err->check( $v[$kcol], $chkval );
				if (!( $err->clear )) {
					$err_flg  = true;
					break;
				}
			}
			if ($err_flg) {
				break;
			}
			foreach ( $maxlens as $kk => $vv ) {
				$err_mes[$kk] =$err->check_size($v[$kk], $vv);
				if (!( $err->clear )) {
					$err_flg  = true;
					break;
				}
			}
			
			if ( !empty($v["contractor"]) ) {
				if (empty(  $arrmst[1][ $v["contractor"] ] )) {
					$err->clear = false ;
					$err_mes["contractor"] =  "制作業者はコードマスタに存在しません";
					break;
				}
			}
			
			if ( !empty($v["print"]) ) {
				if (empty(  $arrmst[2][ $v["print"] ] )) {
					$err->clear = false ;
					$err_mes["print"] =  "印刷業者はコードマスタに存在しません";
					break;
				}
			}
			
			if (empty($v["area_id"]) && strlen($v["area_id"] )<= 0 ) {
				$err->clear = false ;
				$err_mes["area_id"] =  "エリアはコードマスタに存在しません";
				break;
			}
			
			if (empty($v["pattern_cd"]) &&  strlen($v["pattern_cd"]) <= 0 ) {
				$err->clear = false ;
				$err_mes["pattern_cd"] =  "地域新聞名はコードマスタに存在しません";
				break;
			} 
			
			if ($err_flg) {
				break;
			}
				/*			
			if ($v["exp_ins_flg"] == "1") {

				if ( empty($v["exp_ins_week"]) ) {
					$err->clear = false ;
					$err_mes["exp_ins_week"] =  $v["exp_ins_week"]."例外折込は「設定する」場合、入力必須です";
					break;
				} 
				
			}else  {
				//$values[$k]["exp_ins_week"] = "";
			}
			*/
		}
	}
}
//データを抽出する
$dataiterm   = $dao1->get( $matrix_cd );
$formdata["matrix_cd"]  = $matrix_cd;
$formdata["year4"]      = $dataiterm["year4"];
$formdata["week_cd"]    = $dataiterm["week_cd"];
$formdata["week_seq"]   = $dataiterm["week_seq"];
$the_flier_date         = $dataiterm["flier_date"];
$formdata["flier_date"] = Class_PWD::int8_to_dateD( $the_flier_date ) ;



if( $forms['mode'] == 'input' ){
	//foreach ($values as $k => $v ) {
		
	//}
	if( $err->clear ){
		foreach ($values as $k => $v ) {
			if ($v["exp_ins_flg"] != "1") {
				$values[$k]["exp_ins_week"] = $the_flier_date ;
			}
		}
		try {
			$dao->begin_trans();
			$executeflg = TRUE;
			foreach ($values as $k => $v ) {
				if( $vidarr[$k] == '' ){
					if ($id = $dao->add($v)) {
						//$values[$k]['id'] = $id;
					} else {
						$executeflg = FALSE;
						break;
					}
				}else{
					if ($dao->edit( $vidarr[$k], $v )) {
					} else {
						$executeflg = FALSE;
						break;
					}
				}
			}
			
			if  ($executeflg) {
				$dao->commit_trans();
				//$smarty->assign('message', '保存が完了しました。');
				$sqlmessage = $forms["title"]."の保存が完了しました。";
			} else {
				$dao->rollback_trans();
				//$smarty->assign('message', '保存が失敗しました。');
				$err->clear = false ;
				$sqlmessage = $forms["title"]."の保存が失敗しました。";
			}
		} catch (Exception $e) {
			$dao->rollback_trans();
			//$smarty->assign('message', 'ＤＢエラーで失敗しました。');
			$err->clear = false ;
			$sqlmessage = $forms["title"]."の保存が失敗しました。ＤＢエラー";
		}
		$phase = 'input';
	}else{
		$phase = 'input';
	}

}



$where[]  = "matrix_cd = '{$matrix_cd}'";
$verdata = $dao->search($where);
$groupid  = -1;
$group_index = -1;
$maxgroupid =0;
foreach ($verdata as $k=>$v) {
	if ($groupid != $v["groupid"]) {
		if ($groupid != -1) {
			$formdata[$group_index]["d"] = $detail;
		}
		$groupid = $v["groupid"];
		if ($groupid > $maxgroupid) {
			$maxgroupid = $groupid;
		}
		$group_index = $group_index + 1;
		$formdata["groupid"][$group_index]         = $v["groupid"];
		$formdata[$group_index]["h"]["title"]      = $v["title"];
		$formdata[$group_index]["h"]["color"]      = $v["color"];
		$formdata[$group_index]["h"]["sale_name"]  = $v["sale_name"];
		$formdata[$group_index]["h"]["title"]      = $v["title"];
		$formdata[$group_index]["h"]["groupid"]    = $v["groupid"];
		$formdata[$group_index]["h"]["oper"]       = $v["oper"];
		
		$tempT  = "";
		$u_date =  Class_PWD::dateTime_to_dateD($v["u_time"], $tempT);
		$formdata[$group_index]["h"]["u_time"]     =$u_date.substr($v["u_time"],10,9);
		
		$detail = array();
		$detail_index = 0;
	}
	
	$detail[$detail_index]["id"]               = $v["id"];
	$detail[$detail_index]["verno"]            = $v["verno"];
	$detail[$detail_index]["size"]             = $v["size"];
	$detail[$detail_index]["contractor"]       = $v["contractor"];
	$detail[$detail_index]["print"]            = $v["print"];
	$detail[$detail_index]["area_id"]          = $v["area_id"];
	$detail[$detail_index]["area"]             = $v["area"];
	$detail[$detail_index]["pattern_name"]     = $patterns[ $v["pattern_cd"] ];
	$detail[$detail_index]["mano_out"]         = $v["mano_out"];
	$detail[$detail_index]["mano_in"]          = $v["mano_in"];
	$detail[$detail_index]["perweekver"]       = $v["perweekver"];
	$detail[$detail_index]["map"]              = $v["map"];
	$detail[$detail_index]["saletickt"]        = $v["saletickt"];
	$detail[$detail_index]["block_copy_type"]  = $v["block_copy_type"];
	$detail[$detail_index]["exp_ins_flg"]      = $v["exp_ins_flg"];
	
	$detail[$detail_index]["exp_ins_week"]     = Class_PWD::dateTime_to_dateD($v["exp_ins_week"]);

	$detail[$detail_index]["memo"]             = $v["memo"];
	$detail[$detail_index]["user_flag"]        = $v["user_flag"];
	$detail[$detail_index]["memoprinter"]      = $v["memoprinter"];
	
	$detail_index = $detail_index + 1;
}
$formdata[$group_index]["d"] = $detail;
$formdata["maxgroupid"]    = $maxgroupid + 1;
$formdata["maxgroupindex"] = $maxgroupid + 1;

//保存該当$group_index計算
$groupid = $forms["groupid"];
$group_index = $group_index + 1;
$$group_index_exit = false; 

foreach ($formdata["groupid"] as $k=>$v ) {
	if ($groupid == $v) {
		$group_index  = $k ;
		$group_index_exit = true;
	} 
}

if (isset($err) && (!( $err->clear ))) {
	
	if (!$group_index_exit) {
		$formdata["groupid"][$group_index] = $groupid;
		$formdata["maxgroupindex"]  = $maxgroupid + 2;
		
	}
	$errfields = $dao->get_errorfields();
	$errmsg = "";

	foreach ($err_mes as $k=>$v) {
		if (!empty($v)) {
			$errmsg =$errmsg.$errfields[$k]." : ".$v;
		}
	}
	//画面のデータを戻す
	$formdata[$group_index]["h"]["title"]      = $forms["title"];
	$formdata[$group_index]["h"]["color"]      = $forms["color"];
	$formdata[$group_index]["h"]["sale_name"]  = $forms["sale_name"];
	$formdata[$group_index]["h"]["title"]      = $forms["title"];
	$formdata[$group_index]["h"]["groupid"]    = $forms["groupid"];
	$formdata[$group_index]["h"]["oper"]       = $forms["oper"];
	
	$formdata[$group_index]["h"]["errmsg"]     = $errmsg;
	
	$detail = array();
	$detail_index = 0;
	foreach ($forms["size"] as $k => $v ) {
		$detail[$detail_index]["id"]               = $forms["id"][$k] ;
		$detail[$detail_index]["verno"]            = $forms["verno"][$k] ;
		$detail[$detail_index]["size"]             = $forms["size"][$k] ;
		$detail[$detail_index]["contractor"]       = $forms["contractor"][$k] ;
		$detail[$detail_index]["print"]            = $forms["print"][$k] ;
		$detail[$detail_index]["area_id"]          = $forms["area_id"][$k] ;
		
		$detail[$detail_index]["area"]             = $forms["area"][$k] ;
		$detail[$detail_index]["pattern_name"]     = $forms["pattern_name"][$k] ;
		
		$detail[$detail_index]["mano_out"]         = $forms["mano_out"][$k] ;
		$detail[$detail_index]["mano_in"]          = $forms["mano_in"][$k] ;
		$detail[$detail_index]["perweekver"]       = $forms["perweekver"][$k] ;
		$detail[$detail_index]["map"]              = $forms["map"][$k] ;
		$detail[$detail_index]["saletickt"]        = $forms["saletickt"][$k] ;
		$detail[$detail_index]["exp_ins_flg"]      = $forms["exp_ins_flg"][$k] ;
		$detail[$detail_index]["exp_ins_week"]     = $forms["exp_ins_week"][$k] ;
		$detail[$detail_index]["memo"]             = $forms["memo"][$k] ;
		
		$detail[$detail_index]["user_flag"]        = $forms["user_flag"][$k] ;
		$detail[$detail_index]["memoprinter"]             = $forms["memoprinter"][$k] ;
		$detail_index = $detail_index + 1;
	}
	$formdata[$group_index]["d"] = $detail;
}
if ($sqlmessage) {
	$formdata[$group_index]["h"]["errmsg"]     = $sqlmessage;
}


if( isset( $formdata ) ) $smarty->assign('forms',  $formdata);
if( isset( $err_mes ) )  $smarty->assign('err',    $err_mes);

$smarty->assign('isG7', $isG7 );

$smarty->assign('contractors', $arrmst['1'] );
$smarty->assign('prints'     , $arrmst['2'] );
$smarty->assign('areas'      , $arrmst['3'] );

$smarty->assign('size', $aoki_matrix_size );


$smarty->assign('patterns', $patterns );

$matrix_area = $aoki_matrix_area;
$media = Class_M_OTHER::get_media(NULL);
$smarty->assign('map_sort', $aoki_map_sort );

$smarty->assign('opers', $aoki_matrix_oper );


	//print_r($media);
	/*
	 * 
	foreach($media as $k=>$v) {
		$matrix_area[$v["cd"]] = $v["name"];
	}
	$smarty->assign('area', $matrix_area );
	*/
	
$smarty->assign('exp_ins_flg', $aoki_set_flags );
$smarty->assign('user_flag', $aoki_user_flags );
//$smarty->assign('exp_ins_week', $aoki_matrix_weeks );

if ($ispost){
	$smarty->assign('group_index', $group_index );
}
  $smarty->assign('insweekdisabled', true );

$smarty->assign('phase',  $phase );
$smarty->assign('menu',   $smarty->fetch('menu.html') );
$smarty->assign('logout', $smarty->fetch('logout.html') );
$smarty->assign('footer', $smarty->fetch('footer.html') );

$smarty->display('mmatrix_form_ver.html');
?>